package com.meituan.catering.management.shop.biz.service.impl;

import com.meituan.catering.management.common.model.biz.PageBO;
import com.meituan.catering.management.common.model.biz.UserContextBO;
import com.meituan.catering.management.common.model.enumeration.BusinessTypeEnum;
import com.meituan.catering.management.shop.api.http.model.enumeration.ManagementTypeEnum;
import com.meituan.catering.management.shop.api.http.model.request.SearchShopHttpRequest;
import com.meituan.catering.management.shop.biz.model.ShopBO;
import com.meituan.catering.management.shop.biz.model.converter.ShopBOConverter;
import com.meituan.catering.management.shop.biz.service.ShopBizService;
import com.meituan.catering.management.shop.dao.mapper.ShopMapper;
import com.meituan.catering.management.shop.dao.model.ShopDO;
import com.meituan.catering.management.shop.dao.model.request.SearchShopDataRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * {@link ShopBizService}的核心实现
 */
@Service
@Slf4j
public class ShopBizServiceImpl implements ShopBizService {
    @Resource
    private ShopMapper shopMapper;

    public PageBO<ShopBO> searchForPage(UserContextBO userContext, SearchShopHttpRequest request) {
        SearchShopDataRequest dataRequest = this.buildDataRequest(userContext, request);
        /*
         * 返回满足条件的数目
         */
        int totalCount = this.shopMapper.countForPage(dataRequest);
        PageBO<ShopBO> shopPageBO = this.buildPageBO(request, totalCount);
        if (totalCount > 0) {
            List<ShopDO> shopDOs = this.shopMapper.searchForPage(dataRequest);
            shopPageBO.getRecords().addAll(shopDOs.stream().map(ShopBOConverter::fromDO).collect(Collectors.toList()));
        }
        return shopPageBO;
    }

    /**
     * 根据商户号查询单个门店的详细信息
     *
     * @param userContextBO 头部信息(用户号，租户号)
     * @param businessNo    门店号
     * @return ShopBO
     */

    @Override
    public ShopBO findByBusinessNo(UserContextBO userContextBO, String businessNo) {
        ShopDO shopDO = shopMapper.findByBusinessNo(userContextBO.getTenantId(), businessNo);
        if (shopDO == null) {
            throw new IllegalArgumentException("无法找到businessNo：" + businessNo + " 的门店");
        } else {
            return ShopBOConverter.fromDO(shopDO);
        }

    }

    /**
     * 构建 DO 请求体
     *
     * @param userContext 头部信息(用户号，租户号)
     * @param request 查询请求体
     * @return SearchShopDataRequest
     */
    private SearchShopDataRequest buildDataRequest(UserContextBO userContext, SearchShopHttpRequest request) {
        SearchShopDataRequest searchShopDataRequest = new SearchShopDataRequest();
        searchShopDataRequest.setTenantId(userContext.getTenantId());
        searchShopDataRequest.setSkip((request.getPageIndex() - 1) * request.getPageSize());
        searchShopDataRequest.setSize(request.getPageSize());
        if (request.getCondition().getEnabled() != null) {
            searchShopDataRequest.setEnabled(request.getCondition().getEnabled() ? 1 : 0);
        }

        if (request.getCondition().getKeyword() != null && !request.getCondition().getKeyword().equals("")) {
            searchShopDataRequest.setKeyword("%" + request.getCondition().getKeyword() + "%");
        }
        /*
         * 模糊匹配
         */
        if (StringUtils.isNotBlank(request.getCondition().getKeyword())) {
            searchShopDataRequest.setHasKeywords(true);
            searchShopDataRequest.setName(MessageFormat.format("%{0}%", request.getCondition().getKeyword()));
            searchShopDataRequest.setContactTelephone(MessageFormat.format("%{0}%", request.getCondition().getKeyword()));
            searchShopDataRequest.setContactCellphone(MessageFormat.format("%{0}%", request.getCondition().getKeyword()));
            searchShopDataRequest.setContactName(MessageFormat.format("%{0}%", request.getCondition().getKeyword()));
            searchShopDataRequest.setContactAddress(MessageFormat.format("%{0}%", request.getCondition().getKeyword()));
        }


        Set<String> businessTypeNames = new LinkedHashSet<>();
        Set<String> managementTypeNames = new LinkedHashSet<>();
        List<String> sortStr = new LinkedList<>();
        /*
         * 处理set 主营业态
         */
        for (BusinessTypeEnum data : request.getCondition().getBusinessTypes()) {
            businessTypeNames.add(String.valueOf(data));
        }
        searchShopDataRequest.setBusinessTypeNames(businessTypeNames);
        /*
         * 处理set 管理类型
         */
        for (ManagementTypeEnum data : request.getCondition().getManagementTypes()) {
            managementTypeNames.add(String.valueOf(data));
        }
        searchShopDataRequest.setManagementTypeNames(managementTypeNames);

        /*
         * 处理排序逻辑
         */

        for (SearchShopHttpRequest.SortField data : request.getSortFields()) {
            String sortRule = data.getAsc() ? "ASC" : "DESC";
            String field = data.getField();
            /*
             * 拼接排序字符串
             */
            sortStr.add(field + " " + sortRule);
        }
        searchShopDataRequest.setSortByClause(sortStr);


        return searchShopDataRequest;
    }

    private PageBO<ShopBO> buildPageBO(SearchShopHttpRequest request, int totalCount) {
        PageBO<ShopBO> shopPageBO = new PageBO();
        shopPageBO.setTotalCount(totalCount);
        shopPageBO.setPageSize(request.getPageSize());
        shopPageBO.setTotalPageCount(totalCount / request.getPageSize() + (totalCount % request.getPageSize() == 0 ? 0 : 1));
        if (request.getPageIndex() > shopPageBO.getTotalPageCount()) {
            shopPageBO.setPageIndex(shopPageBO.getTotalPageCount());
        } else {
            shopPageBO.setPageIndex(request.getPageIndex());
        }

        return shopPageBO;
    }


}
